package com.cskaoyan.controller;
import com.cskaoyan.bean.Register;
import com.cskaoyan.bean.SmsSendResult;
import com.cskaoyan.bean.data.WxLoginData;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.domain.MarketUser;
import com.cskaoyan.service.AuthService;
import com.cskaoyan.service.SmsService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/wx/auth")
public class WxAuthController {
    @Autowired
    SmsService smsService;
    @Autowired
    AuthService authService;

    private static String realCode = null;

    @PostMapping("/login")
    public BaseRespVo login(@RequestBody Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        subject.login(usernamePasswordToken);
        MarketUser principal = (MarketUser) subject.getPrincipal();
        WxLoginData.UserInfoBean userInfoBean = new WxLoginData.UserInfoBean(principal.getNickname(), principal.getAvatar());
        WxLoginData token = new WxLoginData(userInfoBean, ((String) subject.getSession().getId()));
        return BaseRespVo.ok(token);
    }


    @RequestMapping("logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }
    @PostMapping("/regCaptcha")
    public BaseRespVo regCaptcha(@RequestBody Map map) {
        String mobile = (String) map.get("mobile");
        SmsSendResult smsSendResult = smsService.sendValidationCode(mobile);
        realCode = smsSendResult.getCode();
        System.out.println(smsSendResult.getCode());
        return BaseRespVo.ok();
    }
    @PostMapping("/register")
    public BaseRespVo register(@RequestBody Register register) {
        String code = register.getCode();
        String mobile = register.getMobile();
        String password = register.getPassword();
        String username = register.getUsername();
        return authService.registerUser(code, mobile, password, username, realCode);
    }

    @PostMapping("/reset")
    public BaseRespVo reset(@RequestBody Map map) {
        String code = (String) map.get("code");
        String mobile = (String) map.get("mobile");
        String password = (String) map.get("password");
        return authService.resetUser(code, mobile, password, realCode);

    }
}

